#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :messages_push.py
# Time  :2024/11/26 16:28
# Email :fortunatedong@163.com
# Author:by Adonli
from datetime import datetime
import re

import requests
import toml
from dingding_guotie_jd.settings.logger import Loggings
logs = Loggings()
class MessagePush():
    def __init__(self,message):
        self._cfg = toml.load('settings/config.toml')
        self._robot_url = self._cfg['DINGROBOT']['robot_url']
        self.message = message

    def success_text_push(self):
        title = "国铁&京东——商品价格"
        guotie_sku_brand_name = self.message["guotie_sku_brand_name"]
        guotie_skus_price = self.message["guotie_skus_price"]
        guotie_sku_name = self.message["guotie_sku_name"]
        guotie_sku_model_code = self.message["guotie_sku_model_code"]
        guotie_sku_id = self.message["guotie_sku_id"]
        guotie_keyword = self.message["guotie_keyword"]
        str_markdown = ""
        at = False
        re_str = re.findall(r'[a-zA-Z0-9]', guotie_sku_model_code)
        re_str_result = "".join(re_str)
        if re_str_result :
            title_str = re_str_result
        else:
            title_str = guotie_sku_model_code
        logs.info(f"国铁商城商品型号: {guotie_sku_model_code}")
        logs.info(f"用于京东搜索关键词: {guotie_keyword}")
        for i in range(0,len(self.message["search_jingdong_price"])):
            if self.message["search_jingdong_price"][i]["code"] == 0 :
                logs.info(f"关键词: {title_str} 是否存在京东搜索结果商品名称中：{self.message["search_jingdong_price"][i]["jingdong_ware_name"]}")
                jingdong_res_str = re.findall(r'[a-zA-Z0-9]', self.message["search_jingdong_price"][i]["jingdong_ware_name"])
                jingdong_re_str_result = "".join(jingdong_res_str)
                if jingdong_re_str_result:
                    jingdong_title_str = jingdong_re_str_result
                else:
                    jingdong_title_str = self.message["search_jingdong_price"][i]["jingdong_ware_name"]
                if guotie_skus_price > float(self.message["search_jingdong_price"][i]["jingdong_sell_price"]) and title_str in jingdong_title_str:
                    if self.message["search_jingdong_price"][i]["jingdong_shop"] in str_markdown and "查询到的商品价格没有高于国铁商品销售价格" in str_markdown:
                        str_markdown = ""
                    else:
                        str_markdown =str_markdown
                    markdown= f"{i+1}. <font color=\"#9400D3\">{self.message["search_jingdong_price"][i]["jingdong_shop"]}:</font> {self.message["search_jingdong_price"][i]["jingdong_ware_name"]}价格为<font color=\"#FF0000\">{self.message["search_jingdong_price"][i]["jingdong_sell_price"]}元</font>\n\n"
                    str_markdown += markdown
                    at = True
                else:
                    if self.message["search_jingdong_price"][i]["jingdong_shop"] in str_markdown:
                        continue
                    else:
                        markdown = f"{i + 1}. <font color=\"#9400D3\">{self.message["search_jingdong_price"][i]["jingdong_shop"]}:</font> 查询到的商品价格没有高于国铁商品销售价格\n\n"
                        str_markdown += markdown
            else :
                markdown = f"{i + 1}. <font color=\"#9400D3\">{self.message["search_jingdong_price"][i]["jingdong_shop"]}:</font> {self.message["search_jingdong_price"][i]["search_result"]}\n\n"
                str_markdown += markdown
        logs.info(f"最终查询结果汇总MarkDown: {str_markdown}")
        _robot_body_at = {
            "msgtype": "markdown",
            "markdown": {
                "title": title,
                "text": f"### {title}\n\n"
                        f"- #### 国铁商品品牌：<font color=\"#0000CD\">{guotie_sku_brand_name}</font>\n\n"
                        f"- #### 国铁商品名称：<font color=\"#363636\">{guotie_sku_name}</font>\n\n"
                        f"- #### 国铁商品型号：<font color=\"#0000CD\">{guotie_sku_model_code}</font>\n\n"
                        f"- #### 国铁商品销售价格：<font color=\"#0000CD\">{guotie_skus_price}元</font>\n\n"
                        f"- #### 国铁商品SKU：<font color=\"#363636\">{guotie_sku_id}</font>\n\n"
                        f"- #### 京东搜索关键词：<font color=\"#1874CD\">{guotie_keyword}</font>\n\n"
                        f"- #### 商品匹配关键词：<font color=\"#1874CD\">{title_str}</font>\n\n"
                        f"- #### 查询结果：\n\n"
                        f"{str_markdown}\n\n"
                        f"@xxxxxxxxxxxxx",
            },
            "at": {
                "isAtAll": "false",
                "atMobiles": ["xxxxxxxxxxxxxxxxxx"]
            }
        }
        _robot_body = {
            "msgtype": "markdown",
            "markdown": {
                "title": title,
                "text": f"### {title}\n\n"
                        f"- #### 国铁商品品牌：<font color=\"#0000CD\">{guotie_sku_brand_name}</font>\n\n"
                        f"- #### 国铁商品名称：<font color=\"#363636\">{guotie_sku_name}</font>\n\n"
                        f"- #### 国铁商品型号：<font color=\"#0000CD\">{guotie_sku_model_code}</font>\n\n"
                        f"- #### 国铁商品销售价格：<font color=\"#0000CD\">{guotie_skus_price}元</font>\n\n"
                        f"- #### 国铁商品SKU：<font color=\"#363636\">{guotie_sku_id}</font>\n\n"
                        f"- #### 京东搜索关键词：<font color=\"#1874CD\">{guotie_keyword}</font>\n\n"
                        f"- #### 商品匹配关键词：<font color=\"#1874CD\">{title_str}</font>\n\n"
                        f"- #### 查询结果：\n\n"
                        f"{str_markdown}\n\n"
            }
        }
        if at:
            res = requests.post(url=self._robot_url, json=_robot_body_at)
        else:
            # res = requests.post(url=self._robot_url, json=_robot_body)
            pass

    def admin_error_text_push(self):
        code = self.message["code"]
        result = self.message["result"]
        error = self.message["error"]
        retry = self.message["retry"]

        if code == 2:
            error_robot_body_at = {
                "msgtype": "markdown",
                "markdown": {
                    "title": "国铁Price&京东Price——程序终止运行",
                    "text": f"### 国铁Price&京东Price——程序终止运行\n\n"
                            f"- #### 程序报错代码：<font color=\"#0000CD\">{code}</font>\n\n"
                            f"- #### 程序运行状态：<font color=\"#E4080A\">{result}</font>\n\n"
                            f"- #### 程序报错信息：<font color=\"#0000CD\">{error}</font>\n\n"
                            f"- #### 程序已重试：<font color=\"#0000CD\">{retry}</font>\n\n"
                            f"@xxxxxxxxxxxx",
                },
                "at": {
                    "isAtAll": "false",
                    "atMobiles": ["xxxxxxxxxxxxxxxxxxxxx"]
                }
            }
            res = requests.post(url=self._robot_url, json=error_robot_body_at)
    def admin_info_text_push(self):
        code = self.message["code"]
        status = self.message["status"]
        result = self.message["result"]
        update = self.message["update"]
        message_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        if code == 3:
            error_robot_body_at = {
                "msgtype": "markdown",
                "markdown": {
                    "title": "京东商城订单通知——程序运行情况通知",
                    "text": f"### 京东商城订单通知——程序运行情况通知\n\n"
                            f"- #### 程序代码：<font color=\"#E4080A\">{code}</font>\n\n"
                            f"- #### 程序运行状态：<font color=\"#0000CD\">{result}</font>\n\n"
                            f"- #### 处理结果：<font color=\"#0000CD\">{update}</font>\n\n"
                            f"- 机器人通知时间：<font color=\"#4F4F4F\">{message_time}</font>\n\n"
                            f"@xxxxxxxxxxxxxxxxxxx",
                },
                "at": {
                    "isAtAll": "xxxxxxx",
                    "atMobiles": ["xxxxxxxxxx"]
                }
            }
            res = requests.post(url=self._robot_url, json=error_robot_body_at)




